from django.urls import reverse
from django.shortcuts import render, redirect
from app01 import models
from app01.forms.level import LevelModel,LevelModelForm



def level_list(request):
    queryset = models.Leval.objects.filter(active=1)
    return render(request, 'level_list.html', {"queryset": queryset})

def level_add(request):
    if request.method == 'GET':
        form = LevelModelForm()
        return render(request, 'form.html', {'form': form})

    form = LevelModelForm(request.POST)
    if not form.is_valid():
        return render(request, 'form.html',{"form": form})
    print(form.cleaned_data)
    form.save()
    return redirect(reverse('level_list'))

def level_delete(request,pk):
    exists = models.Customer.objects.filter(leval_id=pk).exists()
    if not exists:
        models.Leval.objects.filter(id=pk).update(active=0)
    return redirect(reverse('level_list'))

def level_edit(request,pk):
    level_object = models.Leval.objects.filter(id=pk, active=1).first()
    if request.method == 'GET':
        form = LevelModelForm(instance=level_object)
        return render(request, 'form.html', {'form': form})
    form = LevelModelForm(data=request.POST, instance=level_object)
    if not form.is_valid():
        return render(request, 'form.html',{"form": form})

    form.save()
    return redirect(reverse('level_list'))